package com.qclix.inv.dao;

import com.qclix.inv.Client;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

/**
 * Default XMLClient DAO implementation.<br/>
 * This implementation uses Hibernate
 */
public class HibernateTemplateClientDaoImpl extends HibernateDaoSupport implements ClientDAO {
    @Transactional(propagation = Propagation.SUPPORTS)
    public void addClient(Client client) throws DAOException {
        getHibernateTemplate().saveOrUpdate(client);
    }

    private static final String CLIENTS_COUNT = "select count(client.id) from Client client";
    public long getClientCount() throws DAOException {
        return (Long) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = getSession().createQuery(CLIENTS_COUNT);
                return query.uniqueResult();
            }
        });
    }

    @SuppressWarnings("unchecked")
    public List<Client> getClients() throws DAOException {
        return getHibernateTemplate().loadAll(Client.class);
    }
}
